<?php
namespace App\Exports;

use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

class ExportOrderToWord
{
    protected $params;
    public function __construct($params = [])
    {
        $this->params = $params;
    }

    public function export()
    {
        $params = $this->params;
        $base_query = Order::query()->where('status', Order::STATUS_OVER)->where('end_date', '>=', $params['start_date'])->where('end_date', '<=', $params['end_date']);

        $orders = $base_query->select('payer_zjhm', 'payer_name', 'payer_dwmc', 'start_date', 'end_date', 'days', 'total_amount')->get();

        $Indent_m = new \PhpOffice\PhpWord\Style\Indentation();
        // 设置首行缩进为2个16字体字符            
        $Indent_m->setFirstLine(2*16*20);

        $phpWord = new PhpWord();
        $phpWord->setDefaultFontName('宋体');//设置字体
        $phpWord->setDefaultFontSize(13);//字号
        $section = $phpWord->addSection();//创建空白页
        $section->addText('财务处：');
        $text = "根据我校《关于印发<中国科学技术大学在京房屋使用管理办法（试行）>通知》（校资后字[2023]132号）精神，现将".date('Y年n月j日', strtotime($params['start_date']))."至".date('Y年n月j日', strtotime($params['end_date']))."间入住北京教师流动公寓人员发给贵处，请按规定收取租金。";
        // 正文段落样式，靠左，首行缩进
        $ParagraphfontStyle5 = [
            'align'       => 'left',
            'indentation' => array('firstLine' => $Indent_m->getFirstLine()),
        ];
        $section->addText(htmlspecialchars($text), [], $ParagraphfontStyle5);

        //预定义样式
        $cellRowSpan = ['vMerge' => 'restart', 'valign' => 'center']; //设置可跨行，且文字居中
        $cellRowContinue = ['vMerge' => 'continue'];//使行连接，且无边框线
        $cellColSpan2 = ['gridSpan' => 2, 'valign' => 'center'];//设置跨列
        $cellColSpan4 = ['gridSpan' => 4, 'valign' => 'center'];//设置跨列
        $cellHCenter = ['align' => 'center'];
        $cellLeft = ['align' => 'left'];
        $cellVCenter = ['valign' => 'center'];
        $styleFont = ['name' => '宋体', 'size' => 12];
        $table = $section->addTable(['borderColor' => '666666', 'borderSize' => 6, 'cellMargin' => 50]);

        $headers = ['工资号', '姓名', '单位', '入住日期', '退住日期', '天数', '费用'];
        $table->addRow(500);//第一行
        foreach($headers as $header) {
            $table->addCell(5000, $cellVCenter)->addText($header, $styleFont, $cellHCenter);
        }

        $total_days = 0;
        $total_amounts = 0;
            
        foreach($orders as $order) {
            $table->addRow(500);//table添加行
            $table->addCell(5000, $cellVCenter)->addText($order->payer_zjhm, $styleFont, $cellHCenter);
            $table->addCell(5000, $cellVCenter)->addText($order->payer_name, $styleFont, $cellHCenter);
            $table->addCell(5000, $cellLeft)->addText($order->payer_dwmc, $styleFont, $cellLeft);
            $table->addCell(5000, $cellLeft)->addText(date('Y年n月j日', strtotime($order->start_date)), $styleFont, $cellLeft);
            $table->addCell(5000, $cellLeft)->addText(date('Y年n月j日', strtotime($order->end_date)), $styleFont, $cellLeft);
            $table->addCell(5000, $cellVCenter)->addText($order->days, $styleFont, $cellHCenter);
            $table->addCell(5000, $cellVCenter)->addText($order->total_amount, $styleFont, $cellHCenter);
            
            $total_days += $order->days;
            $total_amounts += $order->total_amount;
        }

        $table->addRow(500); # 合计
        $table->addCell(5000, $cellColSpan2)->addText('合计', $styleFont, $cellHCenter);
        $table->addCell(5000, $cellVCenter)->addText('', $styleFont, $cellHCenter);
        $table->addCell(5000, $cellVCenter)->addText('', $styleFont, $cellHCenter);
        $table->addCell(5000, $cellVCenter)->addText('', $styleFont, $cellHCenter);
        $table->addCell(5000, $cellVCenter)->addText($total_days, $styleFont, $cellHCenter);
        $table->addCell(5000, $cellVCenter)->addText($total_amounts, $styleFont, $cellHCenter);

        $section->addTextBreak(2);//2个换行
        $section->addText('北京教学与管理部', [], ['align'       => 'right',]);
        $section->addText('日期：'.date("Y年n月j日"), [], ['align'       => 'right',]);

        $writer = IOFactory::createWriter($phpWord);
        $title = "北京教学与管理部".date('Y年n月j日', strtotime($params['start_date']))."至".date('Y年n月j日', strtotime($params['end_date']))."租金收取";
        @mkdir(file_local_path('files'), 0777, true);
        $fileName = "files/" . $title . time() . '.docx';
        $writer->save(file_local_path($fileName));
        return $fileName;
        //如果只是保存到服务器的话到这里就好了
        // $file = public_path('/export/') . $fileName;
        // return response()->download($file); //这里将文件下载下来
        
    }
}